using System;
using System.Xml;
using System.IO;
using System.Text;

/// <summary>
/// This class manages a single RssFeed.  It has functionality to add items to create the feed, add items to the 
/// feed, and write the feed to a string.  It manages writing the proper XML tags and formatting the RSS feed.
/// The class has overrideable functions so that the developer may choose to write the RSS feed in any way they 
/// choose.
/// </summary>
public class RssFeedCreator
{
    private RssFeed _feed;

    public RssFeedCreator(string title, string link, string description)
    {
        _feed = new RssFeed(title, link, description);
    }

    public virtual void AddItem(string title, string link, string description)
    {
        _feed.Items.Add(new RssItem(title, link, description));
    }

    public virtual string WriteFeed()
    {
        StringWriter sw = new StringWriter();
        XmlTextWriter writer = new XmlTextWriter(sw);
        // write xml and rss header info
        writer.WriteRaw("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        writer.WriteStartElement("rss");
        writer.WriteAttributeString("version", "2.0");
        // need to fetch real namespace here:
        writer.WriteAttributeString("xmlns:cs", "Commerce Server");
        writer.WriteStartElement("channel");
        writer.WriteElementString("title", _feed.Title);
        writer.WriteElementString("link", _feed.Link);
        writer.WriteElementString("description", _feed.Description);
        // write all item data
        foreach (RssItem item in _feed.Items)
        {
            writer.WriteStartElement("item");
            writer.WriteElementString("title", item.Title);
            writer.WriteElementString("link", item.Link);
            writer.WriteElementString("description", item.Description);
            writer.WriteEndElement();
        }
        writer.WriteEndElement();
        writer.WriteEndElement();
        // close your resources
        writer.Close();
        sw.Close();
        // now write the data to a string to return
        StringBuilder builder = sw.GetStringBuilder();
        return builder.ToString();
    }
}
